package controller;

import helper.Formatter;
import helper.UserSession;

import helper.Formatter;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import model.*;
import org.mybeans.dao.DAOException;

import databeans.*;

/*
 * @Xiao Liang
 * Customer Use Case: View Transaction History
 */
public class CustomerViewTransactionHistoryAction extends Action{

	@SuppressWarnings("unused")
	private PositionDAO positionDAO; 
	private TransactionDAO transactionDAO; 
	private FundHistoryDAOSQL fundHistoryDAOSQL; 
	private FundDAO fundDAO; 

	public CustomerViewTransactionHistoryAction(Model model) {
		positionDAO = model.getPositoinDAO(); 
		fundHistoryDAOSQL = model.getFundHistoryDAOSQL(); 
		transactionDAO = model.getTransactionDAO(); 
		fundDAO = model.getFundDAO(); 
	}

	public String getName() { return "customerViewTransactionHistory.do"; }

	public String perform(HttpServletRequest request) {
        // define target page
		String loginPage = "customer/customer-login.jsp";
		String successPage = "customer/view-transaction-history.jsp";
        
        // Set up the errors list
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        request.setAttribute("page", "trans-hist");
        
        Employee employee = null;
        Customer customer = null;
        
        
        employee = UserSession.getLoggedInEmployee(request);
        if (employee != null) {
            UserSession.removeEmployeeFromSession(request);
            errors.add("This section is closed for employee");
            return loginPage ;
        }
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer == null) {
            errors.add("You need to log in");
            return loginPage;
        }
        
        
		try {
	        

			//get customer id
  			int customerID = customer.getCustomerID(); 
  			Transaction[] transactions = transactionDAO.getTransactions(customerID); 
  			//Transaction[] transactionsList = transactionDAO.getTransactions(customerID); 
  			
  			List<String> transDates = new ArrayList<String>();
  			List<Integer> transIDs = new ArrayList<Integer>();
  			
  			List<String> transDates_submit = new ArrayList<String>();
  			List<String> transDates_execute = new ArrayList<String>();

  			List<String> transTypes = new ArrayList<String>(); 
  			List<String> fundNames = new ArrayList<String>(); 
  			List<Long> numOfShares = new ArrayList<Long>(); 
  			List<Long> sharePrices = new ArrayList<Long>();
  			List<Long> amounts = new ArrayList<Long>(); 
  			List<String> statuses = new ArrayList<String>(); 
  			SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
  			
  			for(int i=0; i<transactions.length; i++){
  				//display fundName
  				int fundID = transactions[i].getFundID();
  				if (fundID != -1) {
                    Fund fund = fundDAO.lookup(fundID);
                    fundNames.add(fund.getName());
                    System.out.println("Fund Name: "+ i+ " "+ fund.getName()); 
                    
  				
	  				/*else {
	  				  fundNames.add("NA - Check Transaction");
	  				}*/
	
	  				transIDs.add(transactions[i].getTransactionID());
	  				
	  				//display transactionDate
	  				if(transactions[i].getExecuteDate()==null){
	  					System.out.println("Execute date is null");
	  					transDates_submit.add(format.format(transactions[i].getSubmissionDate()));
	  					transDates_execute.add(" - ");
	  					//numOfShares.add(Double.valueOf(twoDForm.format(transactions[i].getShares())));
	  				}else{
	  					transDates_submit.add(format.format(transactions[i].getSubmissionDate()));
	  					transDates_execute.add(format.format(transactions[i].getExecuteDate()));
	  				}
	  				numOfShares.add(transactions[i].getShares());
	  				
	  				//transDates.add(format.format(transactions[i].getExecuteDate()));
	  				//System.out.println("Execute Date: "+ i+ " "+ transactions[i].getExecuteDate()); 
	  				
	  				//display transactionType
	  				transTypes.add(Formatter.transactionType(transactions[i].getTransactionType()));
	
	 				System.out.println("Transaction Type: "+ i+ " "+ transactions[i].getTransactionType()); 
	  				
	  				//display shares
	  				//Position position = positionDAO.lookup(customerID, fundID);
	  				//numOfShares.add(position.getShares());
					//System.out.println("Num Of Shares: "+ i+ " "+ position.getShares()); 
					
	  				//display sharePrice
	  				if(transactions[i].getExecuteDate()==null) {
	  				    sharePrices.add(Long.parseLong("-1")); 
	  				}
	  				else {
		 				Date executeDate = transactions[i].getExecuteDate();
		 				Calendar cal = Calendar.getInstance();
		 				cal.setTime(executeDate); 
	  					 FundHistory fundHistory = fundHistoryDAOSQL.lookup(fundID, cal);
	  				     if(fundHistory==null) sharePrices.add(Long.parseLong("0")); 
	  				     else sharePrices.add(fundHistory.getPrice());
	  				}
	  				
					//System.out.println("Share Price: "+ i+ " "+ sharePrices.get(i)); 
	  				
	  				//display amount
	  				amounts.add(transactions[i].getAmount());
					System.out.println("Amount: "+ i+ " "+ transactions[i].getAmount()); 
					
	  				//display status: Pending or Not Pending
	  				if (transactions[i].getExecuteDate() == null ) {
	  				    statuses.add("Pending"); 
	  				}
	  				else {
	  				    statuses.add("Approved");
	  				}
	  				//System.out.println("Status: "+ i+ " "+ statuses.get(i));
  				}
  			}
 
  			//request.setAttribute("transactionsList", transactions);
  			request.setAttribute("transDates", transDates);

  			request.setAttribute("transIDs", transIDs);
  			request.setAttribute("transDates_submit", transDates_submit);
  			request.setAttribute("transDates_execute", transDates_execute);

  			request.setAttribute("transTypes", transTypes);
  			request.setAttribute("fundNames", fundNames);
  			request.setAttribute("numOfShares", numOfShares);
  			request.setAttribute("sharePrices", sharePrices);
  			request.setAttribute("amounts", amounts);
  			request.setAttribute("statuses", statuses); 

	        return successPage;
        } catch (DAOException e) {
        	errors.add(e.getMessage());
        	return successPage;
        }
    }
	
}
